package org.dromara.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.app.appParams.AppDaiLiInfoParams;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.app.domain.SkAppUser;
import org.dromara.app.mapper.SkAppUserMapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.app.domain.bo.SkDailiShengqingBo;
import org.dromara.app.domain.vo.SkDailiShengqingVo;
import org.dromara.app.domain.SkDailiShengqing;
import org.dromara.app.mapper.SkDailiShengqingMapper;
import org.dromara.app.service.ISkDailiShengqingService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 代理申请信息Service业务层处理
 *
 * @author Evacuation
 * @date 2024-07-23
 */
@RequiredArgsConstructor
@Service
public class SkDailiShengqingServiceImpl implements ISkDailiShengqingService {

    private final SkDailiShengqingMapper baseMapper;

    private final SkAppUserMapper skAppUserMapper;

    /**
     * 查询代理申请信息
     *
     * @param id 主键
     * @return 代理申请信息
     */
    @Override
    public SkDailiShengqingVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询代理申请信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 代理申请信息分页列表
     */
    @Override
    public TableDataInfo<SkDailiShengqingVo> queryPageList(SkDailiShengqingBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SkDailiShengqing> lqw = buildQueryWrapper(bo);
        Page<SkDailiShengqingVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的代理申请信息列表
     *
     * @param bo 查询条件
     * @return 代理申请信息列表
     */
    @Override
    public List<SkDailiShengqingVo> queryList(SkDailiShengqingBo bo) {
        LambdaQueryWrapper<SkDailiShengqing> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SkDailiShengqing> buildQueryWrapper(SkDailiShengqingBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SkDailiShengqing> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), SkDailiShengqing::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getCity()), SkDailiShengqing::getCity, bo.getCity());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), SkDailiShengqing::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getIndustryAwareness()), SkDailiShengqing::getIndustryAwareness, bo.getIndustryAwareness());
        return lqw;
    }

    /**
     * 新增代理申请信息
     *
     * @param bo 代理申请信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SkDailiShengqingBo bo) {
        SkDailiShengqing add = MapstructUtils.convert(bo, SkDailiShengqing.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改代理申请信息
     *
     * @param bo 代理申请信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SkDailiShengqingBo bo) {
        SkDailiShengqing update = MapstructUtils.convert(bo, SkDailiShengqing.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SkDailiShengqing entity){
        //TODO 做一些数据校验,如唯一约束
        if (entity.getId()!=null && entity.getState().longValue()==1){
            List<SkAppUser> list = skAppUserMapper.selectList(
                new QueryWrapper<SkAppUser>().lambda()
                    .eq(SkAppUser::getDailiState,1)
                    .eq(SkAppUser::getDailiCityTitle,entity.getCityCode())
            );
            if (list.size()>0){
                throw new RuntimeException("城市【"+entity.getCity()+"]】已有代理用户无法再次添加！");
            }

            //新建后台管理账户

            //没有城市理商
            SkAppUser app = skAppUserMapper.selectById(entity.getUserId());
            app.setDailiState(1L);
            app.setDailiCityTitle(entity.getCityCode());
            skAppUserMapper.updateById(app);
        }
    }

    /**
     * 校验并批量删除代理申请信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
    /**
     * 代理申请
     */
    @Override
    public void proxyApplication(AppDaiLiInfoParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        SkDailiShengqing sk = BeanUtil.copyProperties(params,SkDailiShengqing.class);
        sk.setUserId(userId);
        sk.setState(0L);
        baseMapper.insert(sk);
    }
}
